package com.concurrency.aqs;

import java.util.concurrent.locks.LockSupport;

public class WaitTest {

    public void testWaitMethod(Object lock) {
        try {
            //synchronized (lock) {
                System.out.println(Thread.currentThread().getName()+" begin wait()");
                // wait() 释放锁资源
                //lock.wait();
                // counter=0 阻塞
                LockSupport.park();
                System.out.println(Thread.currentThread().getName()+" end wait()");
            //}
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void testNotifyMethod(Object lock) {
        try {
            //synchronized (lock) {
                System.out.println(Thread.currentThread().getName()+" begin notify()");

                Thread.sleep(5000);
               // lock.notify();

                System.out.println(Thread.currentThread().getName()+" end notify()");
            //}
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Object lock = new Object();
        WaitTest test = new WaitTest();

       Thread t1 =  new Thread(new Runnable() {
            @Override
            public void run() {
                test.testWaitMethod(lock);
            }
        },"threadA");

        Thread t2 =  new Thread(new Runnable() {
            @Override
            public void run() {
                test.testNotifyMethod(lock);
            }
        },"threadB");
        t1.start();
        t2.start();
        try {
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 发放许可  counter=1
        LockSupport.unpark(t1);
        try {
            Thread.sleep(500000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}